package com.starnet.yarnmonitor.security.handler;


import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import com.starnet.yarnmonitor.security.utils.JwtUtil;
import com.starnet.yarnmonitor.security.utils.RedisCache;
import com.starnet.yarnmonitor.yarn.vo.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Data: 2019/10/30
 * @Des: 登陆验证成功处理
 */
@Component
public class JwtLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    RedisCache redisCache;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        User user = (User) authentication.getPrincipal();


        String json = JSONObject.toJSONString(user);
        String jwtToken = JwtUtil.createJWT(json, 86400000L);
        //存入redis
        redisCache.setCacheObject("login:" + user.getUsername(), jwtToken, 1, TimeUnit.DAYS);
          //返回给前端
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("token", jwtToken);
        //签发token
        Result result = Result.success(hashMap);
        response.getWriter().write(JSON.toJSONString(result));
    }
}
